package com.bbs.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bbs.dao.Userdao;
import com.bbs.entity.User;
import com.bbs.service.ModeratorService;
import com.bbs.service.UserService;
import com.bbs.util.ChangeUtil;
import com.bbs.util.CosUtil;
import com.bbs.util.DateUtil;
import com.bbs.util.Page;
import com.bbs.util.Render;
import com.bbs.util.StringUtil;
import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.oreilly.servlet.MultipartRequest; 

public class UserServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_method");
		if("register".equals(method)){
			register(request,response);
		} else if("login".equals(method)){
			login(request,response);
		} else if("quit".equals(method)){
			quit(request,response);
		} else if("managelogin".equals(method)){
			managelogin(request,response);
		} else if("showusers".equals(method)){
			showUsers(request,response);
		} else if("delete".equals(method)){
			delete(request,response);
		} else if("setmoderator".equals(method)){
			setmoderator(request,response);
		} else if("resetmoderator".equals(method)){
			resetModerator(request,response);
		} else if("change".equals(method)){
			change(request,response);
		} else {
			response.sendError(404);
		}
	}
	
	private void change(HttpServletRequest request, HttpServletResponse response) throws IOException {
		CosUtil cu = new CosUtil(request);
		User u = (User) request.getSession().getAttribute("user");
		String userpwd = cu.getParameter("userpwd");
		String email = cu.getParameter("email");
		if(!u.getUserpwd().equals(userpwd)){
			u.setUserpwd(StringUtil.Md5(userpwd));
		}
		u.setHeadpic(cu.getFileNames().get("pic"));
		u.setEmail(email);
		new UserService().update(u);
		request.getSession().setAttribute("user", u);
		response.sendRedirect("index.jspx?_method=usercenter");
	}

	private void resetModerator(HttpServletRequest request,
			HttpServletResponse response) {
		String uid = request.getParameter("id");
		
	}

	/**
	 * 把某个用户设为版主
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void setmoderator(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String uid = (String) session.getAttribute("uid");
		session.removeAttribute("uid");
		String bid = request.getParameter("blocks");
		int row = new ModeratorService().setModerator(Integer.parseInt(uid),Integer.parseInt(bid));
		int row2 = new UserService().setRole(Integer.parseInt(uid));
		response.sendRedirect("user.jspx?_method=showusers");
	}

	/**
	 * 通过id删除用户
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		int row = new UserService().delete(Integer.valueOf(id));
		if(row > 0){
			response.sendRedirect("user.jspx?_method=showuser");
		}
	}

	/**
	 * 查找所有的版主和会员
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void showUsers(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String page1 = request.getParameter("page1");
		String page2 = request.getParameter("page2");
		HttpSession session = request.getSession();
		Page p1 = (Page) session.getAttribute("page1");
		if(p1==null){
			p1 = new Page();
			p1.setTotleSize(new Userdao().getCountByRole(1));
			p1.setPageSize(5);
		}
		Page p2 = (Page) session.getAttribute("page2");
		if(p2==null){
			p2 = new Page();
			p2.setTotleSize(new Userdao().getCountByRole(2));
			p2.setPageSize(5);
		}
		ChangeUtil cu = new ChangeUtil();
		if(page1 != null){
			p1.setCurrentPage(cu.changeStringToInt(page1));
		}
		if(page2 != null){
			p2.setCurrentPage(cu.changeStringToInt(page2));
		}
		List<User> list1 = new UserService().findAllUser(p1);
		List<User> list2 = new UserService().findModerators(p2);
		session.setAttribute("page1", p1);
		session.setAttribute("page2", p2);
		session.setAttribute("userlist", list1);
		session.setAttribute("userwithblocks", list2);
		response.sendRedirect("index.jspx?_method=showuser");
	}

	/**
	 * 管理员登陆验证
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void managelogin(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String name = request.getParameter("managername");
		String pwd = request.getParameter("managerpwd");
		User u = new UserService().findManager(name,StringUtil.Md5(pwd));
		HttpSession session = request.getSession();
		if(u == null){
			session.setAttribute("msg", "用户名或密码错误！");
			response.sendRedirect("index.jspx?_method=manage");
		} else {
			session.setAttribute("manager", u);
			response.sendRedirect("index.jspx?_method=managemain");
		}
	}

	/**
	 * 安全退出
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void quit(HttpServletRequest request, HttpServletResponse response) throws IOException ,ServletException{
		HttpSession session = request.getSession();
		if(session.getAttribute("user") != null){
			User u = (User)session.getAttribute("user");
			u.setState(false);
			new UserService().update(u);
			session.removeAttribute("user");
			response.sendRedirect("index.jspx");
		} else if(session.getAttribute("manager") != null){
			session.removeAttribute("manager");
			response.sendRedirect("index.jspx?_method=manage");
		} else {
			response.sendRedirect("index.jspx");
		}
	}

	/**
	 * 注册用户
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void register(HttpServletRequest request,
			HttpServletResponse response) throws IOException,ServletException {
		
		
		String validatecode = request.getParameter("validatecode");
		         
		boolean isTrue = SimpleImageCaptchaServlet.validateResponse(request, validatecode);
		HttpSession session = request.getSession();
		if(isTrue) {
			String name = request.getParameter("username");
			String pwd = request.getParameter("userpwd");
			String email = request.getParameter("email");
			String createdate = DateUtil.getNow();
			User u = new User();
			
			u = new UserService().findByName(name);
			if(u == null){
				u = new User();
				u.setUsername(name);
				u.setUserpwd(StringUtil.Md5(pwd));
				u.setCreatedate(createdate);
				u.setEmail(email);
				int row = new UserService().register(u);
				if(row > 0){
					session.setAttribute("msg", "注册成功！请登录！");
					response.sendRedirect("index.jspx?_method=login");
				} else {
					session.setAttribute("msg", "注册失败！");
					response.sendRedirect("index.jspx?_method=register");
				}
			} else {
				session.setAttribute("msg", "用户名已存在！");
				response.sendRedirect("index.jspx?_method=register");
			}
		} else {
			session.setAttribute("msg", "验证码输入错误！");
			Render.rend("register", request, response);
		}
		
	}

	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void login(HttpServletRequest request,
			HttpServletResponse response) throws IOException,ServletException {
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		UserService us = new UserService();
		User u = us.login(username, StringUtil.Md5(userpwd));
		HttpSession session = request.getSession();
		if(u != null){
			u.setState(true);
			new UserService().update(u);
			ServletContext application = getServletContext();
			List<User> userList = (List<User>) application.getAttribute("userList");
			if(userList == null) {
				userList = new ArrayList<User>();
			}
			userList.add(u);
			application.setAttribute("userList", userList);
			session.setAttribute("user", u);
			String url = (String)session.getAttribute("url");
			if(url != null) {
				session.removeAttribute("url");
				response.sendRedirect(url);
			} else {
				response.sendRedirect("index.jspx");
			}
		} else {
			session.setAttribute("msg", "用户名或密码错误！");
			response.sendRedirect("index.jspx?_method=login");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
